<template>
  <page-header-wrapper>
    <page-tab-list>
      <div class="table-page-search-box">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :md="8" :sm="24">
              <a-form-item label="店铺名称">
                <a-input placeholder="请输入店铺名称" v-model="queryParam.name" allowClear></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="起止日期">
                <a-range-picker
                  v-model="queryParam.time"
                  format="YYYY-MM-DD"
                  valueFormat="YYYY-MM-DD"
                  :placeholder="['开始时间', '结束时间']"
                />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="">
                <a-button type="primary" @click="getList">查询</a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </page-tab-list>

    <a-card :bordered="false">
      <div class="table-operator" style="display: flex; justify-content: space-between">
        <a-radio-group v-model="queryParam.status" @change="getList">
          <a-radio-button value="-1"> 全部 </a-radio-button>
          <a-radio-button value="1"> 已开启 </a-radio-button>
          <a-radio-button value="2"> 已关闭 </a-radio-button>
        </a-radio-group>

        <div>
          <a-button style="margin-right: 10px" type="primary" @click="handleEdit()" icon="plus">新建</a-button>
          <a-dropdown>
            <a-menu slot="overlay">
              <a-menu-item @click="handleAll('remove', 3)">批量删除</a-menu-item>
              <a-menu-item @click="handleAll('change', 1)" v-if="queryParam.status !== '1'">批量开启</a-menu-item>
              <a-menu-item @click="handleAll('change', 2)" v-if="queryParam.status !== '2'">批量关闭</a-menu-item>
            </a-menu>
            <a-button> 批量操作 </a-button>
          </a-dropdown>
        </div>
      </div>

      <a-divider />
      <a-table
        :rowKey="
          (r, i) => {
            return r.id
          }
        "
        :pagination="{
          total: this.totalCount,
          showSizeChanger: false,
          onChange: this.tablePageChange,
        }"
        :columns="columns"
        :data-source="list"
        :rowSelection="{ selectedRowKeys: this.selectedRowKeys, onChange: this.onSelectChange }"
        :row-key="(record) => record.id"
      >
        <span slot="status" slot-scope="status, item">
          <span class="tag" :style="status | orderStatus"></span>
          <span>
            {{ getStatus(status) }}
          </span>
        </span>

        <span slot="faceStore" slot-scope="faceStore, item">
          <a-tooltip>
            <template slot="title">
              {{ faceStore.map((el) => el.name).join(',') }}
            </template>
            <p class="des">{{ faceStore.map((el) => el.name).join(',') }}</p>
          </a-tooltip>
        </span>

        <span slot="rate" slot-scope="item"> {{ item }}% </span>

        <span slot="giveIntegralStore" slot-scope="item">
          <a-tooltip>
            <template slot="title">
              {{ item.map((el) => el.name).join(',') }}
            </template>
            <p class="des">{{ item.map((el) => el.name).join(',') }}</p>
          </a-tooltip>
        </span>

        <span slot="time" slot-scope="item"> {{ item.start_date }} 至 {{ item.end_date }} </span>

        <span class="action" slot="action" slot-scope="text, record">
          <a-button type="link" size="small" @click="handleEdit(record)">编辑</a-button>
          <a-divider type="vertical" style="margin:0 1px;"/>
          <a-dropdown>
            <a-button type="link" size="small">更多<a-icon type="down" /></a-button>
            <a-menu slot="overlay">
              <a-menu-item>
                <a-popconfirm title="确认删除规则吗？" @confirm="saasSetStatus(record.id, 3)">
                  <a-button type="link" size="small">删除</a-button>
                </a-popconfirm>
              </a-menu-item>
              <a-menu-item>
                <a-button type="link" size="small" :disabled="record.status == 2" @click="saasSetStatus(record.id, 2)">关闭</a-button>
              </a-menu-item>
              <a-menu-item>
                <a-button type="link" size="small" :disabled="record.status == 1" @click="saasSetStatus(record.id, 1)">开启</a-button>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>
      </a-table>
    </a-card>

    <a-modal
      :title="form.rule_id ? '编辑规则' : '创建规则'"
      width="800px"
      v-model="showCreated"
      @ok="onSubmit"
      :afterClose="closeModal"
      :destroyOnClose="true"
      :confirmLoading="btnLoading"
    >
      <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="{ span: 4 }" :wrapper-col="{ span: 14 }">
        <a-form-model-item label="赠送积分比例" prop="rate">
          <div class="flex">
            <div class="auto">
              <a-input-number
                style="width: 100%"
                v-model="form.rate"
                :max="100"
                :min="0"
                :precision="2"
                placeholder="请输入抽成比例"
              />
            </div>
            <span class="num">%</span>
          </div>
        </a-form-model-item>

        <a-form-model-item label="当面付店铺" prop="face_pay_ids">
          <a-select
            v-model="form.face_pay_ids"
            mode="multiple"
            placeholder="请选择当面付店铺"
            allowClear
            :maxTagCount="2"
          >
            <a-select-option :value="item.id" v-for="item of storeList" :key="item.id">{{ item.name }}</a-select-option>
          </a-select>
        </a-form-model-item>

        <a-form-model-item label="赠送店铺" prop="give_integral_ids">
          <a-select allowClear :maxTagCount="2" v-model="form.give_integral_ids" mode="multiple" placeholder="请选择店铺">
            <a-select-option :value="item.id" v-for="item of storeList" :key="item.id">{{ item.name }}</a-select-option>
          </a-select>
        </a-form-model-item>

        <a-form-model-item label="有效时间" prop="time">
          <a-range-picker
            v-model="form.time"
            :show-time="{ format: 'HH:mm' }"
            format="YYYY-MM-DD HH:mm"
            valueFormat="YYYY-MM-DD HH:mm"
            :placeholder="['开始时间', '结束时间']"
          />
        </a-form-model-item>

        <a-form-model-item label="是否开启" prop="status">
          <a-radio-group v-model="form.status">
            <a-radio value="1"> 开启 </a-radio>
            <a-radio value="2"> 关闭 </a-radio>
          </a-radio-group>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </page-header-wrapper>
</template>

<script>
import { setIntegralRules, getIntegralRules, saasGetStore, saasGetList, saasSetStatus } from '@/api/saas/payFaceToFace'

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    align: 'left',
  },
  {
    title: '当面付店铺',
    dataIndex: 'faceStore',
    scopedSlots: {
      customRender: 'faceStore',
    },
    align: 'left',
    width: '200px',
  },
  {
    title: '赠送店铺',
    dataIndex: 'giveIntegralStore',
    scopedSlots: {
      customRender: 'giveIntegralStore',
    },
    align: 'left',
    width: '200px',
  },
  {
    title: '赠送比例',
    dataIndex: 'rate',
    scopedSlots: {
      customRender: 'rate',
    },
    sorter: (a, b) => a.rate - b.rate,
  },
  {
    title: '有效时间',
    scopedSlots: {
      customRender: 'time',
    },
  },
  {
    title: '状态',
    dataIndex: 'status',
    scopedSlots: {
      customRender: 'status',
    },
  },
  {
    title: '创建时间',
    dataIndex: 'created_at',
    scopedSlots: {
      customRender: 'created_at',
    },
  },
  {
    title: '操作',
    width: '180px',
    dataIndex: 'action',
    scopedSlots: {
      customRender: 'action',
    },
  },
]

export default {
  filters: {
    orderStatus(val) {
      if (val == '2') {
        return 'background-color:#faad14;'
      }

      if (val == '1') {
        return 'background-color:#65c817;'
      }
    },
  },

  computed: {
    getStatus() {
      return (status) => {
        let str

        switch (status) {
          case '1':
            str = '已开启'
            break

          case '2':
            str = '已关闭'
            break
        }

        return str
      }
    },
  },

  data() {
    return {
      selectedRowKeys: [],
      form: {
        rate: '0',
        face_pay_ids: [],
        give_integral_ids: [],
        time: [],
        status: '1',
      },
      rules: {
        give_integral_ids: [{ required: true, message: '请至少选择一个', trigger: 'change' }],
        face_pay_ids: [{ required: true, message: '请至少选择一个', trigger: 'change' }],
        rate: [{ required: true, message: '抽成比例不能为空', trigger: 'blur' }],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }],
        time: [{ required: true, message: '请选择时间', trigger: 'change' }],
      },
      showCreated: false,
      btnLoading: false,
      columns,
      queryParam: {
        page: 1,
        limit: 10,
        name: '',
        time: [],
        status: '-1',
      },
      list: [],
      storeList: [],
    }
  },

  created() {
    saasGetStore().then((res) => {
      this.storeList = res.data.list || []
    })
    this.getList()
  },

  methods: {
    // 批量操作
    handleAll(type, status) {
      if (!this.selectedRowKeys.length) {
        this.$message.warn('请先勾选规则')
        return
      }

      let text = '删除'
      if (type === 'change') {
        text = parseInt(status) === 1 ? '开启' : '关闭'
      }

      this.$confirm({
        title: '是否批量' + text + '?',
        onOk: () => {
          this.saasSetStatus(this.selectedRowKeys.join(','), status)
        },
        onCancel() {},
      })
    },

    // 表格选中
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },

    onSubmit() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          this.btnLoading = true
          let form = JSON.parse(JSON.stringify(this.form))

          form.face_pay_ids = form.face_pay_ids.join(',')
          form.give_integral_ids = form.give_integral_ids.join(',')
          let [start_date, end_date] = form.time
          delete form.time

          const res = await setIntegralRules({
            ...form,
            start_date,
            end_date,
          })

          this.btnLoading = false

          if (!res.code) {
            this.$message.success('保存成功！')

            this.tablePageChange(1)
            this.showCreated = false
          } else {
            this.$message.error(res.msg)
          }
        } else {
          return false
        }
      })
    },

    // 关闭弹窗的回调
    closeModal() {
      this.$refs['ruleForm'].resetFields()
      this.form = {
        rate: '0',
        face_pay_ids: [],
        give_integral_ids: [],
        time: [],
        status: '1',
      }
    },

    // 分页请求
    tablePageChange(e) {
      this.queryParam.page = e
      this.getList()
    },

    // 获取数据
    async getList() {
      const hide = this.$message.loading('加载中...', 1000)
      let queryParam = JSON.parse(JSON.stringify(this.queryParam))

      if (queryParam.time.length) {
        queryParam.start_date = queryParam.time[0]
        queryParam.end_date = queryParam.time[1]
      }
      delete queryParam.time

      const res = await saasGetList(queryParam)
      if (res.code == 0) {
        this.list = res.data.data
        this.totalCount = res.data.totalCount
        this.selectedRowKeys = []
      }
      hide()
    },

    async handleEdit(item) {
      // let path = '/payFaceToFace/IntegralRule/edit'
      // if (item) {
      //   path += `?id=${item.id}`
      // }

      // this.$router.push({ path })
      if (item) {
        const res = await getIntegralRules({
          rule_id: item.id,
        })
        let { id, end_date, start_date, status, rate, faceStore, giveIntegralStore } = res.data

        this.form = {
          rate,
          rule_id: id,
          face_pay_ids: faceStore.map((el) => el.id),
          give_integral_ids: giveIntegralStore.map((el) => el.id),
          time: [start_date, end_date],
          status,
        }
      }

      this.showCreated = true
    },

    saasSetStatus(rule_id, status) {
      this.$message.loading({ content: '处理中...', key: 'deleteLoading' })
      saasSetStatus({
        rule_id,
        status,
      }).then((res) => {
        if (res.code == 0) {
          this.tablePageChange()
          this.$message.success({ content: res.msg, key: 'deleteLoading' })
        } else {
          this.$message.warning({ content: res.msg, key: 'deleteLoading' })
        }
      })
    },
  },
}
</script>

<style lang="less" scoped>
.des {
  width: 200px;
  margin-bottom: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.tag {
  display: inline-block;
  width: 6px;
  height: 6px;
  border-radius: 50%;
  margin-right: 4px;
}

.flex {
  display: flex;
  align-items: center;
  overflow: hidden;

  .auto {
    flex: 1;
  }

  .num {
    display: inline-block;
    width: 30px;
    height: 32px;
    display: inline-block;
    background: #f7f7f7;
    color: rgba(0, 0, 0, 0.65);
    line-height: 32px;
    text-align: center;
    border: 1px solid #d9d9d9;
    border-left: 0;
    border-radius: 0 4px 4px 0;
  }
}
</style>
